package com.heima.schedule.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.common.constatns.ScheduleConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.schedule.dtos.Task;
import com.heima.model.schedule.pojos.Taskinfo;
import com.heima.model.schedule.pojos.TaskinfoLogs;
import com.heima.schedule.mapper.TaskinfoLogsMapper;
import com.heima.schedule.mapper.TaskinfoMapper;
import com.heima.schedule.service.TaskService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.*;


@Service
@Transactional
@Slf4j
public class TaskServiceImpl implements TaskService {

    @Autowired
    private TaskinfoMapper taskinfoMapper;

    @Autowired
    private TaskinfoLogsMapper taskinfoLogsMapper;

    @Autowired
    private CacheService cacheService;


    /**
     * 添加任务
     *
     * @param task 任务对象
     * @return 任务id
     */
    @Override
    public long addTask(Task task) {


        //1添加任务到数据库
        boolean success = addTask2Db(task);
        if (success) {
            //2添加任务到redis
            addTask2Cache(task);
        }
        return task.getTaskId();
    }

    /**
     * 取消任务
     *
     * @param taskId
     * @return
     */
    @Override
    public boolean cancelTask(long taskId) {
        boolean flag = false;

        //删除任务 更新任务日志
        Task task = updateDb(taskId, ScheduleConstants.CANCELLED);

        //删除redis中的数据
        if (task != null) {
            removeTaskFromCache(task);
            flag = true;
        }
        return flag;
    }

    /**
     * 按照类型和优先级来拉取任务
     *
     * @param type
     * @param priority
     * @return
     */
    @Override
    public Task poll(int type, int priority) {

        Task task = null;
        try {
            String key = type + "_" + priority;
            //从redis中拉去数据  pop
            String taskJson = cacheService.lRightPop(ScheduleConstants.TOPIC + key);
            if (StringUtils.isNotBlank(taskJson)) {
                task = JSON.parseObject(taskJson, Task.class);
                //修改数据库信息
                task = updateDb(task.getTaskId(), ScheduleConstants.EXECUTED);

            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("poll task exception");
        }
        return task;
    }

    /**
     * 删除redis中的数据
     *
     * @param task
     */
    private void removeTaskFromCache(Task task) {

        String key = task.getTaskType() + "_" + task.getPriority();
        if (task.getExecuteTime() <= System.currentTimeMillis()) {
            cacheService.lRemove(ScheduleConstants.TOPIC + key, 0, JSON.toJSONString(task));
        } else {
            cacheService.zRemove(ScheduleConstants.FUTURE + key, JSON.toJSONString(task));
        }
    }

    /**
     * 更新任务日志
     *
     * @param taskId
     * @param status
     * @return
     */
    private Task updateDb(long taskId, int status) {

        Task task = null;
        try {
            //1.删除任务
            taskinfoMapper.deleteById(taskId);

            //2.更新任务日志
            TaskinfoLogs taskinfoLogs = taskinfoLogsMapper.selectById(taskId);
            taskinfoLogs.setStatus(status);
            taskinfoLogsMapper.updateById(taskinfoLogs);

            task = new Task();
            BeanUtils.copyProperties(taskinfoLogs, task);
            task.setExecuteTime(taskinfoLogs.getExecuteTime().getTime());
        } catch (Exception e) {
            log.error("task cancel exception taskId={}", taskId);
        }
        return task;
    }

    /**
     * 添加任务到redis中
     *
     * @param task
     */
    private void addTask2Cache(Task task) {

        String key = task.getTaskType() + "_" + task.getPriority();
        //获取5分钟之后的时间
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE, 5);
        long nextScheduleTime = calendar.getTimeInMillis();

        //当前时间
        long currentTime = System.currentTimeMillis();
        if (task.getExecuteTime() <= currentTime) {
            //1如果任务的执行时间小于当前时间， 存入list
            log.info("当前任务的发布时间小于当前时间(当前数据)，存入list");
            cacheService.lLeftPush(ScheduleConstants.TOPIC + key, JSON.toJSONString(task));
        } else if (task.getExecuteTime() <= nextScheduleTime) {
            log.info("当前任务的发布时间小于5分钟（未来数据），存入zset");
            //2如果任务的执行时间大于当前时间 并且小于等于 预设时间  存入zset中
            cacheService.zAdd(ScheduleConstants.FUTURE + key, JSON.toJSONString(task), task.getExecuteTime());
        }else {
            log.info("当前任务的发布时间大于5分钟,不存入redis");
        }
    }

    /**
     * 添加任务到数据库
     *
     * @param task
     * @return
     */
    private boolean addTask2Db(Task task) {

        boolean flag = false;
        try {
            //1.保存任务表
            Taskinfo taskinfo = new Taskinfo();
            BeanUtils.copyProperties(task, taskinfo);
            //类型转换
            Date date = new Date(task.getExecuteTime());
            taskinfo.setExecuteTime(date);
            taskinfoMapper.insert(taskinfo);

            task.setTaskId(taskinfo.getTaskId());
            //2.保存任务日志数据
            TaskinfoLogs taskinfoLogs = new TaskinfoLogs();
            BeanUtils.copyProperties(taskinfo, taskinfoLogs);
            taskinfoLogs.setVersion(1);
            taskinfoLogs.setStatus(ScheduleConstants.SCHEDULED);
            taskinfoLogsMapper.insert(taskinfoLogs);
            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }


    /**
     * redis中的未来数据定时刷新
     */
    @Scheduled(cron = "0 */1 * * * ?")
    public void refresh() {

        //TODO 分布式锁
        String token = cacheService.tryLock("FUTURE_TASK_SYNC", 1000 * 30);
        if (StringUtils.isNotBlank(token)) {
            log.info("未来数据定时刷新==>将zset中的数据刷新到list中");
            //获取所有未来数据的集合key
            Set<String> futureKeys = cacheService.scan(ScheduleConstants.FUTURE + "*");
            for (String futureKey : futureKeys) {  //future_100_50


                //获取当前数据的集合key topic  (topic_100_50)
                String topicKey = ScheduleConstants.TOPIC + futureKey.split(ScheduleConstants.FUTURE)[1];
                //按照key和分值查询复合条件的数据 ( >=0&&<=当前时间的 key
                Set<String> tasks = cacheService.zRangeByScore(futureKey, 0, System.currentTimeMillis());

                //同步数据
                if (!tasks.isEmpty()) {
                    cacheService.refreshWithPipeline(futureKey, topicKey, tasks);
                    System.out.println("成功的将" + futureKey + "下的当前需要执行的任务数据刷新到" + topicKey + "下");
                }
            }
        } else {
            log.info("获取redis未来数据刷新的锁失败");
        }
    }

    /**
     * 数据库任务定时同步到redis中
     */
    @Scheduled(cron = "0 */5 * * * ?")
    @PostConstruct  //初始化函数 项目启动时启动
    public void reloadData() {
        log.info("数据库同步数据到redis中");
        //TODO 分布式锁
        String token = cacheService.tryLock("DB_TO_REDIS_SYNC", 1000 * 60);
        if (StringUtils.isNotBlank(token)) {
            //清理缓存中的数据  list Zset
            clearCache();

            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.MINUTE, 5);
            Date nextScheduleTime= calendar.getTime();

            //查询符合条件的任务 小于未来5分钟的数据
            LambdaQueryWrapper<Taskinfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.le(Taskinfo::getExecuteTime,nextScheduleTime);


            List<Taskinfo> allTasks = taskinfoMapper.selectList(lambdaQueryWrapper);
            if (allTasks != null && allTasks.size() > 0) {
                for (Taskinfo taskinfo : allTasks) {
                    Task task = new Task();
                    BeanUtils.copyProperties(taskinfo,task);
                    task.setExecuteTime(taskinfo.getExecuteTime().getTime());
                    //把任务添加到redis中
                    addTask2Cache(task);
                }
            }
            log.info("数据库的任务同步到了redis缓存");
        }
    }

    public void clearCache() {

        // 删除缓存中未来数据集合和当前消费者队列的所有key
        Set<String> topicKeys = cacheService.scan(ScheduleConstants.TOPIC + "*");
        Set<String> futureKeys = cacheService.scan(ScheduleConstants.FUTURE + "*");

        cacheService.delete(topicKeys);
        cacheService.delete(futureKeys);

    }
}
